#!/usr/bin/env python3
"""
调试数据库路径的脚本
"""

import os
from app import app, db, Prompt
from datetime import datetime

def debug_database():
    """调试数据库路径和连接"""
    with app.app_context():
        print("=" * 50)
        print("数据库调试信息")
        print("=" * 50)
        
        # 显示当前工作目录
        print(f"当前工作目录: {os.getcwd()}")
        
        # 显示数据库URI
        print(f"数据库URI: {app.config['SQLALCHEMY_DATABASE_URI']}")
        
        # 显示数据库文件路径
        db_uri = app.config['SQLALCHEMY_DATABASE_URI']
        if db_uri.startswith('sqlite:///'):
            db_path = db_uri.replace('sqlite:///', '')
            print(f"数据库文件路径: {db_path}")
            print(f"数据库文件是否存在: {os.path.exists(db_path)}")
            if os.path.exists(db_path):
                print(f"数据库文件大小: {os.path.getsize(db_path)} 字节")
        
        # 测试数据库连接
        print(f"\n数据库连接测试:")
        try:
            # 检查表是否存在
            result = db.session.execute(db.text("SELECT name FROM sqlite_master WHERE type='table' AND name='prompts'")).fetchone()
            print(f"prompts表是否存在: {result is not None}")
            
            if result:
                # 检查记录数
                count_result = db.session.execute(db.text("SELECT COUNT(*) FROM prompts")).scalar()
                print(f"直接SQL查询记录数: {count_result}")
                
                # 检查所有记录
                records = db.session.execute(db.text("SELECT id, chrome_id, text FROM prompts LIMIT 5")).fetchall()
                print(f"直接SQL查询记录:")
                for record in records:
                    print(f"  ID: {record[0]}, Chrome ID: {record[1]}, Text: {record[2][:50]}...")
            
        except Exception as e:
            print(f"数据库连接测试失败: {e}")
        
        # 测试SQLAlchemy查询
        print(f"\nSQLAlchemy查询测试:")
        try:
            count = Prompt.query.count()
            print(f"SQLAlchemy查询记录数: {count}")
            
            if count > 0:
                prompts = Prompt.query.limit(3).all()
                print(f"SQLAlchemy查询记录:")
                for prompt in prompts:
                    print(f"  ID: {prompt.id}, Chrome ID: {prompt.chrome_id}, Text: {prompt.text[:50]}...")
                    
        except Exception as e:
            print(f"SQLAlchemy查询测试失败: {e}")

if __name__ == '__main__':
    debug_database()
